import React, { useState, useEffect } from 'react';
import { Table, Input, Button, DatePicker, Card, Space, Tag, Select } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx';
import ReactECharts from 'echarts-for-react';
import OverviewLayout from '../../layouts/OverviewLayout';
import moment from 'moment';

const { Option } = Select;

// 模拟项目数据
const mockProjects = [
    { id: 'P001', name: '城市花园项目' },
    { id: 'P002', name: '商业中心建设' },
    { id: 'P003', name: '地铁延长线工程' },
];

// 模拟仓库数据
const mockWarehouses = [
    {
        id: 'WH001',
        name: '主仓库',
        projectId: 'P001',
        projectName: '城市花园项目',
        location: '工地东侧',
        manager: '张管理员',
        contact: '13800138001',
        area: '5000',
        unit: '平方米',
        capacity: '80%',
        status: '正常运营',
        createTime: '2023-01-10',
        lastInventory: '2023-06-15',
        materialCount: 156,
        remark: '存放主要建材'
    },
    {
        id: 'WH002',
        name: '电气仓库',
        projectId: 'P001',
        projectName: '城市花园项目',
        location: '工地西侧',
        manager: '李管理员',
        contact: '13800138002',
        area: '800',
        unit: '平方米',
        capacity: '65%',
        status: '正常运营',
        createTime: '2023-02-15',
        lastInventory: '2023-06-10',
        materialCount: 89,
        remark: '存放电气设备'
    },
    {
        id: 'WH003',
        name: '临时仓库A',
        projectId: 'P002',
        projectName: '商业中心建设',
        location: 'B区南侧',
        manager: '王管理员',
        contact: '13800138003',
        area: '1200',
        unit: '平方米',
        capacity: '45%',
        status: '临时使用',
        createTime: '2023-03-20',
        lastInventory: '2023-06-05',
        materialCount: 42,
        remark: '临时存放装修材料'
    },
    {
        id: 'WH004',
        name: '设备仓库',
        projectId: 'P003',
        projectName: '地铁延长线工程',
        location: '3号入口附近',
        manager: '赵管理员',
        contact: '13800138004',
        area: '2000',
        unit: '平方米',
        capacity: '75%',
        status: '正常运营',
        createTime: '2023-04-05',
        lastInventory: '2023-06-18',
        materialCount: 112,
        remark: '存放施工设备'
    },
];

const WarehouseOverview = () => {
    const [selectedProject, setSelectedProject] = useState(null);
    const [warehouses, setWarehouses] = useState([]);
    const [filteredWarehouses, setFilteredWarehouses] = useState([]);
    const [filters, setFilters] = useState({
        name: '',
        manager: '',
        status: '',
        startDate: null,
        endDate: null
    });

    // 根据选择的项目筛选仓库
    useEffect(() => {
        if (selectedProject) {
            const filtered = mockWarehouses.filter(wh => wh.projectId === selectedProject);
            setWarehouses(filtered);
            setFilteredWarehouses(filtered);
        } else {
            setWarehouses([]);
            setFilteredWarehouses([]);
        }
    }, [selectedProject]);

    // 处理筛选变化
    const handleFilterChange = (key, value) => {
        const newFilters = { ...filters, [key]: value };
        setFilters(newFilters);
        applyFilters(newFilters);
    };

    // 应用筛选条件
    const applyFilters = (filterParams) => {
        let result = [...warehouses];

        if (filterParams.name) {
            result = result.filter(wh => wh.name.includes(filterParams.name));
        }

        if (filterParams.manager) {
            result = result.filter(wh => wh.manager.includes(filterParams.manager));
        }

        if (filterParams.status) {
            result = result.filter(wh => wh.status.includes(filterParams.status));
        }

        if (filterParams.startDate && filterParams.endDate) {
            result = result.filter(wh => {
                const createTime = moment(wh.createTime);
                return createTime.isAfter(filterParams.startDate) && createTime.isBefore(filterParams.endDate);
            });
        }

        setFilteredWarehouses(result);
    };

    // 导出Excel
    const exportToExcel = () => {
        const worksheet = XLSX.utils.json_to_sheet(filteredWarehouses);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "仓库列表");
        XLSX.writeFile(workbook, `仓库列表_${moment().format('YYYYMMDD_HHmmss')}.xlsx`);
    };

    // 图表配置 - 仓库状态分布
    const warehouseStatusOption = {
        title: {
            text: '仓库状态分布',
            left: '3%',
            top: '3%'
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            right: '5%',
            top: '3%',
            data: ['正常运营', '临时使用', '维护中', '已关闭']
        },
        series: [
            {
                name: '仓库状态',
                type: 'pie',
                radius: '80%',
                center: ['50%', '55%'],
                data: [
                    { value: 8, name: '正常运营' },
                    { value: 3, name: '临时使用' },
                    { value: 1, name: '维护中' },
                    { value: 1, name: '已关闭' }
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };

    // 图表配置 - 仓库容量分布
    const warehouseCapacityOption = {
        title: {
            text: '仓库容量分布',
            top: '3%',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            top: '35%',
            right: '5%',
            left: '5%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: ['主仓库', '电气仓库', '临时仓库A', '设备仓库', '材料仓库B']
        },
        yAxis: {
            type: 'value',
            name: '容量百分比',
            max: 100,
            axisLabel: {
                formatter: '{value}%'
            }
        },
        series: [
            {
                name: '使用容量',
                type: 'bar',
                data: [80, 65, 45, 75, 60],
                itemStyle: {
                    color: function(params) {
                        const value = params.data;
                        if (value > 80) {
                            return '#f5222d'; // 红色表示高使用率
                        } else if (value > 60) {
                            return '#faad14'; // 黄色表示中等使用率
                        } else {
                            return '#52c41a'; // 绿色表示低使用率
                        }
                    }
                }
            }
        ]
    };

    // 表格列配置
    const columns = [
        {
            title: '仓库ID',
            dataIndex: 'id',
            key: 'id',
            width: 100
        },
        {
            title: '仓库名称',
            dataIndex: 'name',
            key: 'name',
            width: 120
        },
        {
            title: '所属项目',
            dataIndex: 'projectName',
            key: 'projectName',
            width: 150
        },
        {
            title: '位置',
            dataIndex: 'location',
            key: 'location',
            width: 120
        },
        {
            title: '管理员',
            dataIndex: 'manager',
            key: 'manager',
            width: 120
        },
        {
            title: '联系方式',
            dataIndex: 'contact',
            key: 'contact',
            width: 120
        },
        {
            title: '面积',
            dataIndex: 'area',
            key: 'area',
            render: (text, record) => `${text} ${record.unit}`,
            width: 120
        },
        {
            title: '当前容量',
            dataIndex: 'capacity',
            key: 'capacity',
            render: capacity => {
                const percent = parseInt(capacity);
                let color = '';
                if (percent > 80) {
                    color = 'red';
                } else if (percent > 60) {
                    color = 'orange';
                } else {
                    color = 'green';
                }
                return <Tag color={color}>{capacity}</Tag>;
            },
            width: 120
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: status => {
                let color = '';
                switch (status) {
                    case '正常运营':
                        color = 'green';
                        break;
                    case '临时使用':
                        color = 'blue';
                        break;
                    case '维护中':
                        color = 'orange';
                        break;
                    case '已关闭':
                        color = 'red';
                        break;
                    default:
                        color = 'gray';
                }
                return <Tag color={color}>{status}</Tag>;
            },
            width: 120
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 120
        },
        {
            title: '最后盘点',
            dataIndex: 'lastInventory',
            key: 'lastInventory',
            width: 120
        },
        {
            title: '物料种类',
            dataIndex: 'materialCount',
            key: 'materialCount',
            width: 100
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            width: 150
        }
    ];

    return (
        <OverviewLayout
            children={{
                topRight:
                    <ReactECharts
                        option={warehouseStatusOption}
                        style={{ height: '100%', width: '100%' }}
                    />,
                topLeft:
                    <ReactECharts
                        option={warehouseCapacityOption}
                        style={{ height: '100%', width: '100%' }}
                    />,
                bottom:
                    <Card
                        title="仓库列表"
                        variant={"outlined"}
                        style={{ height: 'calc((100vh - 64px) * 2 / 3)',zIndex: '100' }}
                        extra={
                            <Space>
                                <Select
                                    placeholder="选择项目"
                                    style={{ width: 200 }}
                                    onChange={(value) => setSelectedProject(value)}
                                    allowClear
                                >
                                    {mockProjects.map(project => (
                                        <Option key={project.id} value={project.id}>
                                            {project.name}
                                        </Option>
                                    ))}
                                </Select>
                                <Button
                                    type="primary"
                                    icon={<DownloadOutlined />}
                                    onClick={exportToExcel}
                                    disabled={!selectedProject}
                                >
                                    导出Excel
                                </Button>
                            </Space>
                        }
                    >
                        {selectedProject ? (
                            <>
                                <Space style={{ marginBottom: 16 }}>
                                    <Input
                                        placeholder="仓库名称"
                                        value={filters.name}
                                        onChange={e => handleFilterChange('name', e.target.value)}
                                        style={{ width: 150 }}
                                    />
                                    <Input
                                        placeholder="管理员"
                                        value={filters.manager}
                                        onChange={e => handleFilterChange('manager', e.target.value)}
                                        style={{ width: 150 }}
                                    />
                                    <Input
                                        placeholder="状态"
                                        value={filters.status}
                                        onChange={e => handleFilterChange('status', e.target.value)}
                                        style={{ width: 150 }}
                                    />
                                    <DatePicker.RangePicker
                                        value={[filters.startDate, filters.endDate]}
                                        onChange={(dates) => {
                                            handleFilterChange('startDate', dates ? dates[0] : null);
                                            handleFilterChange('endDate', dates ? dates[1] : null);
                                        }}
                                    />
                                    <Button
                                        type="default"
                                        onClick={() => {
                                            setFilters({
                                                name: '',
                                                manager: '',
                                                status: '',
                                                startDate: null,
                                                endDate: null
                                            });
                                            setFilteredWarehouses(warehouses);
                                        }}
                                    >
                                        重置
                                    </Button>
                                </Space>
                                <Table
                                    columns={columns}
                                    dataSource={filteredWarehouses}
                                    rowKey="id"
                                    pagination={{ pageSize: 10 }}
                                    scroll={{ x: 1800 }}
                                />
                            </>
                        ) : (
                            <div style={{ textAlign: 'center', padding: '50px 0' }}>
                                <h3>请先选择项目查看仓库信息</h3>
                            </div>
                        )}
                    </Card>
            }}
        />
    );
};

export default WarehouseOverview;